//
//  MapLayersAndCollectedDataView.m
//  dataGathering
//
//  Created by apple on 14/11/10.
//  Copyright (c) 2014年 shuili. All rights reserved.
//

#import "MapLayersAndCollectedDataView.h"
#import "LatestLayerModelManager.h"
#import "MapMainView.h"
#import "MapLayersTableViewCell.h"
#import "SKSTableViewCell.h"
#import "FileUtil.h"


@interface MapLayersAndCollectedDataView ()
@property(nonatomic, retain)collectedDataTableViewController *collectedDataTableVC;
@property(nonatomic, retain)workSet *currentWorkset;

@property(nonatomic, assign)NSInteger selectedIndex;
@property(nonatomic, retain)collectedData *selectedData;

@property(nonatomic, retain)NSMutableArray *mapLayersModelArray;

@property (weak, nonatomic) IBOutlet UIButton *featureLayersButotn;
@property (weak, nonatomic) IBOutlet UIButton *imageLayersButton;
@property (weak, nonatomic) IBOutlet UIView *layersContainerView;

@property (nonatomic, strong) NSArray *featureContents;

@end

@implementation MapLayersAndCollectedDataView
@synthesize featureLayersButotn = _featureLayersButotn;
@synthesize imageLayersButton = _imageLayersButton;
@synthesize layersContainerView = _layersContainerView;
@synthesize mapLayerTypeSwitch = _mapLayerTypeSwitch;

- (void)viewDidLoad {
    [super viewDidLoad];
    _currentWorkset = [[currentWorkSetManager sharedInstance] getCurrentWorkSet];
    
    _mapLayersModelArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relocateScrollView) name:@"dataDetailViewWillPop" object:nil];
    
    [self initScrollView];
    
    [_mapLayersDownloadButton setBackgroundImage:[UIImage imageNamed:@"_btn-primary_-regular_u36_mouseOver.png"] forState:UIControlStateHighlighted];
    
    [_MapLayersButton setBackgroundImage:[UIImage imageNamed:@"u149_selected.png"] forState:UIControlStateHighlighted];
    [_MapLayersButton setBackgroundImage:[UIImage imageNamed:@"u149_selected.png"] forState:UIControlStateSelected];
    [_MapLayersButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [_CollectedDataButton setBackgroundImage:[UIImage imageNamed:@"u149_selected.png"] forState:UIControlStateHighlighted];
    [_CollectedDataButton setBackgroundImage:[UIImage imageNamed:@"u149_selected.png"] forState:UIControlStateSelected];
    [_CollectedDataButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [self setMayLayersButtonSelected:YES];
    
    isFeatureLayersDisplayed = YES;
}

-(void)relocateScrollView
{
    if(_contentScrollView){
        if([_MapLayersButton isSelected]){
            [_contentScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        } else {
            [_contentScrollView setContentOffset:CGPointMake(_contentScrollView.frame.size.width , 0) animated:NO];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initScrollView
{
    //_contentScrollView.pagingEnabled = YES;
    //_contentScrollView.clipsToBounds = NO;

    //_contentScrollView.scrollsToTop = NO;
    _contentScrollView.contentSize = CGSizeMake(482*2, 600);
    
    _contentScrollView.scrollsToTop = NO;
    _contentScrollView.delegate = self;
    
    UIButton *syncButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 15, 40, 40)];
    [syncButton setImage:[UIImage imageNamed:@"pic_绘制方式_u1041.png"] forState:UIControlStateNormal];
    //[_contentScrollView addSubview:syncButton];
    
    UIButton *test = [[UIButton alloc] initWithFrame:CGRectMake(_contentScrollView.frame.size.width+60, 15, 40, 40)];
    //[test setImage:[UIImage imageNamed:@"pic_绘制方式_u1041.png"] forState:UIControlStateNormal];
    [_contentScrollView addSubview:test];
    
    _collectedDataTableVC = [[self childViewControllers] objectAtIndex:0];
    _collectedDataTableVC.selectProtocol = self;
    
    UIButton *manage = [[UIButton alloc] initWithFrame:CGRectMake(_contentScrollView.frame.size.width+38, 536, 418, 40)];
    [manage setTitle:@"组织已采集元素" forState:UIControlStateNormal];
    [manage setTitle:@"批量删除采集元素" forState:UIControlStateSelected];
    [manage setBackgroundImage:[UIImage imageNamed:@"_btn-primary_-regular_u36.png"] forState:UIControlStateNormal];
    [manage setBackgroundImage:[UIImage imageNamed:@"_btn-primary_-regular_u36_selected.png"] forState:UIControlStateSelected];
    [manage addTarget:self action:@selector(managetButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [_contentScrollView addSubview:manage];
    
    [_collectedDataTableVC.tableView setAllowsSelectionDuringEditing:NO];
    
    if (!self.featureContents) {
        
        NSMutableArray *contentsArray = [[NSMutableArray alloc] initWithCapacity:10];
        for (GroupModel *gModel in [[[[LatestLayerModelManager sharedInstance] getLatestLayerModel] feature] groups])
        {
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:10];
            [tempArray addObject:[gModel name]];
            for(LayerModel *lModel in [gModel layers]){
                [tempArray addObject:[lModel name]];
            }
            [contentsArray addObject:tempArray];
        }
        NSMutableArray *outerArray = [[NSMutableArray alloc] initWithCapacity:10];
        [outerArray addObject:contentsArray];
        self.featureContents = outerArray;
        
//        self.featureContents = @[@[@[@"Section0_Row0", @"Row0_Subrow1",@"Row0_Subrow2"],
//                                   @[@"Section0_Row1", @"Row1_Subrow1", @"Row1_Subrow2", @"Row1_Subrow3", @"Row1_Subrow4", @"Row1_Subrow5", 		@"Row1_Subrow6", @"Row1_Subrow7", @"Row1_Subrow8", @"Row1_Subrow9", @"Row1_Subrow10", @"Row1_Subrow11", @"Row1_Subrow12"],
//                                   @[@"Section0_Row2"]],
//                                 @[@[@"Section1_Row0", @"Row0_Subrow1", @"Row0_Subrow2", @"Row0_Subrow3"],
//                                   @[@"Section1_Row1"],
//                                   @[@"Section1_Row2", @"Row2_Subrow1", @"Row2_Subrow2", @"Row2_Subrow3", @"Row2_Subrow4", @"Row2_Subrow5"]]];
    }
    
    self.tableView = [[SKSTableView alloc] initWithFrame:CGRectMake(47, 0, 482-46-1, 596)];
    self.tableView.SKSTableViewDelegate = self;
    
    //self.tableView.frame = CGRectMake(46, 0, 482-46, 596);
    [_contentScrollView addSubview:self.tableView];
    
}
- (IBAction)featureServiceButotnClicked:(id)sender {
    
    
    NSMutableArray *contentsArray = [[NSMutableArray alloc] initWithCapacity:10];
    for (GroupModel *gModel in [[[[LatestLayerModelManager sharedInstance] getLatestLayerModel] feature] groups])
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:10];
        [tempArray addObject:[gModel name]];
        for(LayerModel *lModel in [gModel layers]){
            [tempArray addObject:[lModel name]];
        }
        [contentsArray addObject:tempArray];
    }
    NSMutableArray *outerArray = [[NSMutableArray alloc] initWithCapacity:10];
    [outerArray addObject:contentsArray];
    [self.tableView removeFromSuperview];
    self.featureContents = outerArray;
    
    self.tableView = [[SKSTableView alloc] initWithFrame:CGRectMake(47, 0, 482-46-1, 596)];
    self.tableView.SKSTableViewDelegate = self;
    [_contentScrollView addSubview:self.tableView];
    [self.tableView reloadData];
    
    isFeatureLayersDisplayed = YES;
}
- (IBAction)mapLayersButtonClicked:(id)sender {
    NSMutableArray *contentsArray = [[NSMutableArray alloc] initWithCapacity:10];
    for (MapGroupModel *gModel in [[[[LatestLayerModelManager sharedInstance] getLatestLayerModel] map] groups])
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:10];
        [tempArray addObject:[gModel name]];
        for(MapLayerModel *lModel in [gModel layers]){
            [tempArray addObject:[lModel name]];
        }
        [contentsArray addObject:tempArray];
    }
    NSMutableArray *outerArray = [[NSMutableArray alloc] initWithCapacity:10];
    [outerArray addObject:contentsArray];
    [self.tableView removeFromSuperview];
    self.featureContents = outerArray;
    
    self.tableView = [[SKSTableView alloc] initWithFrame:CGRectMake(47, 0, 482-46-1, 596)];
    self.tableView.SKSTableViewDelegate = self;
    self.featureContents = outerArray;
    [_contentScrollView addSubview:self.tableView];
    [self.tableView reloadData];
    isFeatureLayersDisplayed = NO;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.featureContents count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.featureContents[section] count];
}

- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.featureContents[indexPath.section][indexPath.row] count] - 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SKSTableViewCell";
    
    SKSTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell)
        cell = [[SKSTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    cell.textLabel.text = self.featureContents[indexPath.section][indexPath.row][0];
    NSLog(@"indexpath section is %ld, row is %ld, text is %@",(long)indexPath.section,(long)indexPath.row,self.featureContents[indexPath.section][indexPath.row][0]);
    
    //if ((indexPath.section == 0 && (indexPath.row == 1 || indexPath.row == 0)) || (indexPath.section == 1 && (indexPath.row == 0 || indexPath.row == 2)))
    if (indexPath.section == 0)
        cell.isExpandable = YES;
    else
        cell.isExpandable = NO;
    
    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    //static NSString *CellIdentifier = @"MapLayersTableViewCell";
    
    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    //if (!cell)
        //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    MapLayersTableViewCell *cell;
    
    static  NSString *identifier = @ "mapLayersTableViewCell" ;
    
    cell = (MapLayersTableViewCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if  (!cell) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@ "MapLayersTableViewCell"  owner:nil options:nil];
        cell = [nib objectAtIndex:0];
    }
    NSString *typeString = [NSString stringWithFormat:@"%@", self.featureContents[indexPath.section][indexPath.row][indexPath.subRow]];
    [cell setMainLabelString:typeString];
    
    if(isFeatureLayersDisplayed){
        if([FileUtil checkIfFileDownloaded:[typeString stringByAppendingString:@".sqlite"] :FileTypeFeatureData])
        {
            [cell setDownloadButtonString:@"删除"];
        }
    } else {
        if([FileUtil checkIfFileDownloaded:[typeString stringByAppendingString:@".tpk"] :FileTypeTPK])
        {
            [cell setDownloadButtonString:@"删除"];
        }
        
    }
    if([[[currentWorkSetManager sharedInstance] getCurrentWorkSet] isOnlineLayerDisplayed]){
        for (UIView* next = [[self navigationController].parentViewController.view superview]; next; next = next.superview) {
            UIResponder* nextResponder = [next nextResponder];
            if ([nextResponder isKindOfClass:[UIViewController class]]) {
                [cell setVisibleStatus:[((MapMainView*)nextResponder) checkIfMapLayersIsVisible:typeString]];
            }
        }
    }
    
    
    //cell.textLabel.text = [NSString stringWithFormat:@"    %@", self.featureContents[indexPath.section][indexPath.row][indexPath.subRow]];
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView.contentOffset.x >= scrollView.contentSize.width/2.0){
        [_CollectedDataButton setSelected:YES];
        [_MapLayersButton setSelected:NO];
    } else {
        [_CollectedDataButton setSelected:NO];
        [_MapLayersButton setSelected:YES];
    }
}

-(void)managetButtonClicked:(id)sender
{
    UIButton *button = (UIButton*)sender;
    if([button isSelected]){
        [button setSelected:NO];
        
        NSArray *deletedList = [_collectedDataTableVC.tableView indexPathsForSelectedRows];
        for(NSIndexPath *indexpath in deletedList){
            [[_currentWorkset collectedDataList] removeObjectAtIndex:[indexpath row]];
        }
        
        [_collectedDataTableVC.tableView setAllowsMultipleSelectionDuringEditing:NO];
        [_collectedDataTableVC.tableView setEditing:NO animated:YES];
        [_collectedDataTableVC.tableView reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"collectedDataRemoved" object:nil];
        
    } else {
        [button setSelected:YES];
        [_collectedDataTableVC.tableView setAllowsMultipleSelectionDuringEditing:YES];
        [_collectedDataTableVC.tableView setEditing:YES animated:YES];
        
    }
}


- (IBAction)toMaplayersSection:(id)sender {
    [self setMayLayersButtonSelected:YES];
}

- (void)setMayLayersButtonSelected: (BOOL)selected
{
    [_MapLayersButton setSelected:selected];
    [_CollectedDataButton setSelected:!selected];
    
    [_contentScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)setCollectedDataButtonSelected: (BOOL)selected
{
    [_CollectedDataButton setSelected:selected];
    [_MapLayersButton setSelected:!selected];
    
    [_contentScrollView setContentOffset:CGPointMake(_contentScrollView.frame.size.width+6 , 0) animated:YES];
}

- (void)callCollectedDataDetailView:(NSInteger)index :(collectedData *)selectedData
{
    _selectedIndex = index;
    _selectedData = selectedData;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showSelectedData" object:selectedData];
    [self performSegueWithIdentifier:@"toCollectedDataDetailView" sender:nil];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue identifier] && [[segue identifier] compare:@"toCollectedDataDetailView"] == NSOrderedSame){
        
        ((collectedDataDetailView*)[segue destinationViewController]).currentData = _selectedData;
        ((collectedDataDetailView*)[segue destinationViewController]).index = _selectedIndex;

    } else if([segue identifier] && [[segue identifier] compare:@"toSelectedDataDetailView"] == NSOrderedSame){
        
    }
}


- (IBAction)collectedDataButtonClicked:(id)sender {
    [self setCollectedDataButtonSelected:YES];
}

-(void)callSelectedDataDetailView :(collectedData*)data
{
    collectedDataDetailView *selectedDataViewVC = [self.storyboard instantiateViewControllerWithIdentifier:@"collectedDataDetailView"];
    [selectedDataViewVC setCurrentData:data];
    [selectedDataViewVC setMode:5];//Just set a random number to indicate it's in another mode
    selectedDataViewVC.view.frame = CGRectMake(0, 0, 482, 660);
    
    NSLog(@"name is %@", [data name]);
    
    selectedDataViewVC.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self presentViewController:selectedDataViewVC animated:NO completion:nil];
    //[self.view.window.rootViewController presentViewController:selectedDataViewVC animated:NO completion:nil];
    
    
}
- (IBAction)swipeAction:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"closeMapLayerView" object:nil];
}

/*
#pragma tableview datasource and delegates
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger tableCount = 0;
    [_mapLayersModelArray removeAllObjects];
    if([_mapLayerTypeSwitch isOn]){
        
        for(GroupModel *gModel in [[[[LatestLayerModelManager sharedInstance] getLatestLayerModel] feature] groups])
        {
            tableCount = tableCount + [[gModel layers] count];
            [_mapLayersModelArray addObjectsFromArray:[gModel layers]];
            
        }

    } else {
        for(MapGroupModel *gModel in [[[[LatestLayerModelManager sharedInstance] getLatestLayerModel] map] groups])
        {
            tableCount = tableCount + [[gModel layers] count];
            [_mapLayersModelArray addObjectsFromArray:[gModel layers]];
        }
    }
    
    return tableCount;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //UITableViewCell *cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 480, 48)];
    
    MapLayersTableViewCell *cell;
    
    static  NSString *identifier = @ "mapLayersTableViewCell" ;
    
    cell = (MapLayersTableViewCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if  (!cell) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@ "MapLayersTableViewCell"  owner:nil options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    
    UIColor *typeTextColor = [UIColor colorWithRed:77.0/256.0 green:77.0/256.0 blue:77.0/256.0 alpha:1];
    UIColor *nameTextColor = [UIColor colorWithRed:151.0/256.0 green:151.0/256.0 blue:150.0/256.0 alpha:1];
    
    NSUInteger row = [indexPath row];
    
    UILabel *namelabel = [[UILabel alloc] initWithFrame:CGRectMake(96, 8, 300 , 19)];
    if([_mapLayerTypeSwitch isOn]){
        cell.mainLabelString = [(LayerModel*)[_mapLayersModelArray objectAtIndex:row] name];
        [namelabel setText:[(LayerModel*)[_mapLayersModelArray objectAtIndex:row] name]];
    } else {
        cell.mainLabelString = [(MapLayerModel*)[_mapLayersModelArray objectAtIndex:row] name];
        [namelabel setText:[(MapLayerModel*)[_mapLayersModelArray objectAtIndex:row] name]];
    }
    
    [namelabel setTextColor:typeTextColor];
    [namelabel setFont:[UIFont systemFontOfSize:16]];

    //[cell addSubview:namelabel];
    
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    for (UIView* next = [[self navigationController].parentViewController.view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            if([_mapLayerTypeSwitch isOn]){
                [((MapMainView*)nextResponder) setSelectedLayerVisibleUsingName:[(LayerModel*)[_mapLayersModelArray objectAtIndex:[indexPath row]] name] visible:YES];
            } else {
                [((MapMainView*)nextResponder) setSelectedLayerVisibleUsingName:[(MapLayerModel*)[_mapLayersModelArray objectAtIndex:[indexPath row]] name] visible:YES];
            }
        }
    }
}                                       

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    for (UIView* next = [[self navigationController].parentViewController.view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            if([_mapLayerTypeSwitch isOn]){
                [((MapMainView*)nextResponder) setSelectedLayerVisibleUsingName:[(LayerModel*)[_mapLayersModelArray objectAtIndex:[indexPath row]] name] visible:NO];
            } else {
                [((MapMainView*)nextResponder) setSelectedLayerVisibleUsingName:[(MapLayerModel*)[_mapLayersModelArray objectAtIndex:[indexPath row]] name] visible:NO];
            }
        }
    }
}
 */

- (IBAction)downloadMaplayersButtonClicked:(id)sender {
    for (NSIndexPath *path in [_mapLayersTableView indexPathsForSelectedRows])
    {
        if([_mapLayerTypeSwitch isOn])
        {
            //(LayerModel*)[_mapLayersModelArray objectAtIndex:[path row]]
        }
    }
}



@end
